/*
 * @Description:
 * @Author: Junhuang
 * @Date: 2022-02-15 13:49:18
 * @LastEditTime: 2022-05-24 17:35:01
 * @LastEditors: Junhuang
 * @Reference:
 */

'use strict';

const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');


// 异步二进制写入流
const awaitWriteStream = require('await-stream-ready').write;
// 管道读入一个虫洞
const sendToWormhole = require('stream-wormhole');
const dayjs = require('dayjs');
// const { resolve } = require('path');

class FileController extends Controller {
  async upload() {
    const { ctx, service } = this;
    let user_path = 'unknown';
    if (ctx.authUser) {
      user_path = ctx.authUser.id;
    } else if (ctx.authAdmin) {
      user_path = 'admin' + ctx.authAdmin.id;
    }
    const stream = await this.ctx.getFileStream();
    // 基础的目录
    const uploadBasePath = 'app/public/uploads';
    // 生成文件名
    const filename = `${Date.now()}${Number.parseInt(
      Math.random() * 1000
    )}${path.extname(stream.filename).toLocaleLowerCase()}`;
    // 生成文件夹
    const dirname = dayjs(Date.now()).format('YYYY/MM/DD');
    function mkdirsSync(dirname) {
      if (fs.existsSync(dirname)) {
        return true;
      }

      // path.dirname(filepath) 表示获得该文件地址的目录；
      // 例如：filepath = app/public/uploads/2022/02/15 则path.filepath = app/public/uploads/2022/02
      if (mkdirsSync(path.dirname(dirname))) {
        fs.mkdirSync(dirname);
        return true;
      }

    }
    mkdirsSync(path.join(uploadBasePath, dirname));
    // 生成写入路径
    const target = path.join(uploadBasePath, dirname, filename);
    // 写入流
    const writeStream = fs.createWriteStream(target);
    let url = '';
    try {
      // 异步把文件流 写入
      await awaitWriteStream(stream.pipe(writeStream));
      // cos_filename 是拼接了用户的目录后，在cos上存放的文件名（即带目录的文件名）
      const cos_filename = '/' + user_path + '/' + filename;
      const res_cos = await service.cos.docos(cos_filename, target);
      fs.unlinkSync(target);
      url = res_cos.Location;
      const result = await service.cos.pic_ContentReview(cos_filename);
      console.log('图片内容审核结果:', result);
      if (result) {
        if (result.Result > 0) {
          // 图片内容审核不通过,则在腾讯云中删除该对象，此可以是异步操作
          service.cos.deleteObject(cos_filename);
          return ctx.apiFail('图片内容审核不通过:' + result.Label);
        }
      }
    } catch (err) {
      // 如果出现错误，关闭管道
      await sendToWormhole(stream);
      this.ctx.throw(500, err);
    }

    // const { protocol } = this.ctx.request;
    // let url = path.join('/public/uploads', dirname, filename).replace(/\\|\//g, '/');
    // 在数据库中仅存储相对路径，主机地址则在页面段进行配置
    // url = protocol + '://' + this.app.config.webUrl + url;

    console.log('url=', url);
    ctx.apiSuccesss({ url });
  }

  // 获取COS签名
  async geCOSAuth() {
    const { ctx, service } = this;
    console.log('query=', ctx.query);
    const authorization = service.cos.getAuth({
      ...ctx.query,
      SecretId: 'AKIDb1ANJzNUKuDF0TkkSt4ybx3rOegRv83m',
      SecretKey: 'UgbFcjZ8QRBernRoujHYYHjSu53j8H9k', // 私钥
    });
    ctx.apiSuccesss(authorization);
  }

}

module.exports = FileController;
